#!/usr/bin/env python3.11
# -*- encoding: utf-8 -*-
"""
@File    :   controllers.py
@Time    :   2024/04/11 15:56:15
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from django.shortcuts import get_object_or_404
from ninja_extra import api_controller, route
from ninja_extra.pagination import (
    PageNumberPaginationExtra,
    PaginatedResponseSchema,
    paginate,
)
from .models import Student
from .schema import StudentSchema, CreateStudentSchema, MessageSchema,UpdateStudentSchema


@api_controller("/students", tags=["学生管理"])
class StudentsController:
    @route.get("/info", summary="学生信息", url_name="students-info")
    def get_students_info(
        self,
    ):
        return {"message": "students info"}

    @route.get(
        "/list",
        summary="学生列表",
        response=PaginatedResponseSchema[StudentSchema],
        url_name="students_list",
    )
    @paginate(PageNumberPaginationExtra, page_size=10)
    def get_students_list(
        self,
    ):
        return Student.objects.all()

    @route.post(
        "",
        summary="新增学生",
        response=[(201, StudentSchema), (400, MessageSchema)],
        url_name="add-student",
    )
    def add_student(
        self,
        data: CreateStudentSchema,
    ):
        try:
            obj = data.create_obj()
            return 201, obj
        except Exception as ex:
            return 400, {"code":1,"message": "创建失败"}
        
    @route.get(
        "/{sno}", 
        summary="获取学生信息",
        response= StudentSchema,
        url_name="get-student"
    )
    def get_student_by_sno(self, sno: int):
        obj = get_object_or_404(Student,sno=sno)
        return obj
             
    @route.delete(
        "/{sno}", 
        summary="删除学生", 
        response=[(200, MessageSchema), (400, MessageSchema)],
        url_name="delete-student"
    )
    def delete_student(self, sno: int):
        try:
            obj =  get_object_or_404(Student,sno=sno)
            obj.delete()
            return 200,{"code":0,"message": "删除成功"}
        except Exception as ex:
            return 400, {"code":1,"message": "删除失败"}
    
    @route.post(
        "/{sno}", 
        summary="修改学生", 
        response= StudentSchema,
        url_name="update-student"
    )
    def update_student(self, sno: int,data: UpdateStudentSchema):
        obj = get_object_or_404(Student,sno=sno)
        data.update(obj)
        return obj
